/*****************************************************************************
*                                                                           *
* Amazon S3 Command Shell  (s3shell)                                        *
*                                                                           *
* Copyright (C) 2008 Sumit Birla <http://sumitbirla.com>                    *
*                                                                           *
*                                                                           *
* This program is free software; you can redistribute it and/or modify      *
* it under the terms of the GNU General Public License as published by      *
* the Free Software Foundation; either version 2 of the License, or         *
* (at your option) any later version.                                       *
*                                                                           *
* This program is distributed in the hope that it will be useful,           *
* but WITHOUT ANY WARRANTY; without even the implied warranty of            *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             *
* GNU General Public License for more details.                              *
*                                                                           *
* You should have received a copy of the GNU General Public License         *
* along with this program; if not, write to the Free Software               *
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA  *
*                                                                           *
*****************************************************************************/

package com.sumitbirla.s3shell;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;
import com.amazon.s3.*;

/**
 *
 * @author sbirla
 */
public class Acct extends Command {
    
    public Acct(Environment env) {
        super(env);
    }
    
    @Override
    public void execute(String[] params, InputStream is, OutputStream os) {
        try {
            // if sub-command was not passed in, return
            if (params.length < 2)
            {
                os.write(getUsage().getBytes());
                return;
            }
            
            String cmd = params[1];
            
            if (cmd.equals("add"))
                addAccount(params[2], params[3], params[4]);
            else if (cmd.equals("del"))
                deleteAccount(params[2]);
            else if (cmd.equals("use")) {
                useAccount(params[2]);
                String msg = "Switched to account: [" + params[2] + "]\n";
                os.write(msg.getBytes());
            }
            else if (cmd.equals("list")) {
                List items = getList();
                StringBuffer sb = new StringBuffer();
            
                // print the total number of buckets first
                sb.append("total " + items.size() + "\n");

                // print out creation date and name of each bucket
                for(Iterator it = items.iterator(); it.hasNext();)
                {
                    sb.append(it.next());
                    sb.append("\n");          
                } 
                
                os.write(sb.toString().getBytes());
            }
            else 
                os.write(getUsage().getBytes());
                   
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    public String getUsage() {
        return "acct [list|add|del|use] name [accessKeyId secretKey]\n";
    }
    
    private void addAccount(String name, String accessKey, String secretKey)  
        throws Exception
    {
        for(int i = 0; i < 10; i++)
        {
            String str = env.prefs.get("account_name" + i, "");
            if (str.equals("")) {
                env.prefs.put("account_name" + i, name);
                env.prefs.put("account_access_key" + i, accessKey);
                env.prefs.put("account_secret_key" + i, secretKey);
                return;
            }
        }
        
        throw new Exception("No slots remaining.");
    }
    
    private void deleteAccount(String name) 
        throws Exception
    {
        for(int i = 0; i < 10; i++)
        {
            String str = env.prefs.get("account_name" + i, "");
            if (str.equals(name)) {
                env.prefs.put("account_name" + i, "");
                env.prefs.put("account_access_key" + i, "");
                env.prefs.put("account_secret_key" + i, "");
                return;
            }
        }
        
        throw new Exception("Account not found.");
    }
    
    private void useAccount(String name) 
        throws Exception
    {
        for(int i = 0; i < 10; i++)
        {
            String str = env.prefs.get("account_name" + i, "");
            if (str.equals(name)) {
                String awsAccessKeyId = env.prefs.get("account_access_key" + i, "");
                String awsSecretAccessKey = env.prefs.get("account_secret_key" + i, "");
                env.s3conn = new AWSAuthConnection(awsAccessKeyId, awsSecretAccessKey);
                env.account = name;
                env.prefs.put("last_account", name);
                return;
            }
        }
        
        throw new Exception("Account not found.");
    }
    
    private List getList() 
    {
        ArrayList accounts = new ArrayList();
        
        for(int i = 0; i < 10; i++)
        {
            String name = env.prefs.get("account_name" + i, "");
            if (!name.equals(""))
                accounts.add(name);
        }
        
        return accounts;
    }
}
